package com.nvn.washiodriver.network.ws;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;

import android.annotation.SuppressLint;
import android.content.Context;

import com.nvn.washiodriver.Objects.LatLng;
import com.nvn.washiodriver.Objects.Order;
import com.nvn.washiodriver.Objects.OrderStatus;
import com.nvn.washiodriver.network.NetworkUtils;
import com.nvn.washiodriver.network.WebServiceCommunicatorListener;
import com.nvn.washiodriver.utils.GMapV2Utils;
import com.nvn.washiodriver.utils.Statics;
import com.parse.ParseUser;

@SuppressLint("SimpleDateFormat")
public class GetOrderListWSControl extends BaseWSControl {
	private String userId;
	private GMapV2Utils md;
	private Document doc;

	public GetOrderListWSControl(Context context,
			WebServiceCommunicatorListener listener, String userId) {
		super(context, listener, WebServiceFlag.GET_ORDER);
		this.userId = userId;
		md = new GMapV2Utils();
	}

	@Override
	protected Object doInBackground(Void... params) {
		// Get local database

		Date d = new Date();
		String startDateTime = new SimpleDateFormat(
				"yyyy-MM-dd'T'00:00:00-07:00").format(d);
		String endDateTime = new SimpleDateFormat("yyyy-MM-dd'T'23:59:59-07:00")
				.format(d);

		// TEST
//		String  startDateTime = new SimpleDateFormat(
//		 "yyyy-05-09'T'00:00:00-07:00").format(d);
//		String  endDateTime = new SimpleDateFormat("yyyy-05-09'T'23:59:59-07:00")
//		 .format(d);

		String url = Statics.WASHIO_WS_URL + "driver/orders?userId=" + userId
				+ "&startDateTime=" + startDateTime + "&endDateTime="
				+ endDateTime + "&cityId=" + Statics.cityId;

		try {
			String respone = NetworkUtils.doRequest(url);
			try {
				JSONObject job = new JSONObject(respone);
				return getOrderFromJSONObject(Statics.getJSONArray(job,
						"orders"));

			} catch (JSONException e) {
				mError = e.getMessage();
			}

		} catch (ClientProtocolException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		} catch (IOException e) {
			mError = "Cannot connect to network";
			e.printStackTrace();
		}
		return null;
	}

	public ArrayList<Order> getOrderFromJSONObject(JSONArray jArray)
			throws JSONException {
		ArrayList<Order> orders = new ArrayList<Order>();

		for (int i = 0; i < jArray.length(); i++) {
			Order o = new Order();
			JSONObject job = jArray.getJSONObject(i);

			o.setObjectId(Statics.getString(job, "id"));

			JSONObject driverPickup = Statics.getJSONObject(
					Statics.getJSONObject(job, "pickupShiftActual"), "user");
			JSONObject driverDropoff = Statics.getJSONObject(
					Statics.getJSONObject(job, "dropoffShiftActual"), "user");
			String curUserId = ParseUser.getCurrentUser().getObjectId();
			o.setServiceType(Statics.getString(job, "serviceType"));
			o.setPickUp(false);
			o.setDropOff(false);
			o.setTime("?");

			if (Statics.getString(driverPickup, "id").equals(curUserId)) {
				o.setPickUp(true);
				o.setTime(Statics.getString(job, "pickupTime"));
			} else if (Statics.getString(driverDropoff, "id").equals(curUserId)) {
				o.setDropOff(true);
				o.setTime(Statics.getString(job, "dropoffTime"));
			}

			o.setLaundryCount(Statics.getInt(job, "laundryBagsCount"));
			o.setDryCleanCout(Statics.getInt(job, "dryCleaningBagsCount"));
			o.setDriverNote(Statics.getString(job, "driverSpecialInstructions"));
			o.setCusNote(Statics.getString(job, "customerSpecialInstructions"));
			o.setAdminNote(Statics.getString(job, "adminSpecialInstructions"));

			JSONObject jAddress = Statics.getJSONObject(job, "address");
			String address = Statics.getString(jAddress, "address") + " "
					+ Statics.getString(jAddress, "apartmentNumber");
			o.setAddress(address.trim());
			o.setAdressNote(Statics.getString(jAddress, "note"));
			o.setZip(Statics.getString(jAddress, "zip"));
			
			String lat = Statics.getString(jAddress, "latitude");
			String lon = Statics.getString(jAddress, "longitude");
			o.setLatitude(lat);
			o.setLongitude(lon);

			// TEST
			// Statics.curLat = 34.053228;
			// Statics.curLon = -118.24693;

			if (Statics.curLat != 0) {
				try {
					doc = md.getDocument(new LatLng(Statics.curLat,
							Statics.curLon), new LatLng(lat, lon),
							GMapV2Utils.MODE_DRIVING);
					o.setEsDistance(md.getDistanceText(doc).replaceAll("mi",
							"miles"));
					o.setEsTime(md.getDurationText(doc));
				} catch (Exception e) {
					o.setEsDistance("_Miles Away");
					o.setEsTime("ETA_min");
				}

			} else {
				o.setEsDistance("_Miles Away");
				o.setEsTime("ETA_min");
			}

			JSONObject jUser = Statics.getJSONObject(jAddress, "user");
			o.setCustomer(Statics.getString(jUser, "firstName") + " "
					+ Statics.getString(jUser, "lastName"));
			o.setPhone(Statics.getString(jUser, "phone"));
			o.setVip(Statics.getBoolean(jUser, "isVip"));

			JSONObject jStatus = Statics.getJSONObject(job, "status");
			OrderStatus oStatus = new OrderStatus();
			oStatus.setObjectId(Statics.getString(jStatus, "id"));
			oStatus.setOrdinalValue(Statics.getString(jStatus, "ordinalValue"));
			oStatus.setOrdinalValueClient(Statics.getString(jStatus,
					"ordinalValueClient"));
			oStatus.setsClient(Statics.getString(jStatus, "statusClient"));
			oStatus.setsLookup(Statics.getString(jStatus, "statusLookup"));
			oStatus.setStatus(Statics.getString(jStatus, "status"));

			o.setoStatus(oStatus);

			orders.add(o);

		}

		return orders;
	}
}
